/*****************************************************************************
 * hal_stm32_uart.c
 *
 * Copyright (C) 2019 Jeasonvor <1101627719@qq.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 ****************************************************************************/

/*****************************************************************************
 * Included Files
 ****************************************************************************/

#include "plum_api.h"
#include "hal/source/hal_stm32f1/hal_stm32f1.h"
/*****************************************************************************
 * Trace Definitions
 ****************************************************************************/

/*****************************************************************************
 * Pre-processor Definitions
 ****************************************************************************/

/*****************************************************************************
 * Private Types
 ****************************************************************************/
struct stm32_uart {
    UART_HandleTypeDef huart;

    plum_u8 rxbyte;
    fifo_t  rxfifo;

#if defined(PLUM_OS)
    plum_sem_ref_t uart_rx_sem;
    plum_sem_ref_t uart_tx_sem;
#else

#endif

    struct stm32_uart *next;
};

/*****************************************************************************
 * Private Function Prototypes
 ****************************************************************************/

/*****************************************************************************
 * Private Data
 ****************************************************************************/

PLUM_PRIVATE struct stm32_uart uarts_hd;

/*****************************************************************************
 * Public Data
 ****************************************************************************/

/*****************************************************************************
 * Private Functions
 ****************************************************************************/

/*
 * @brief:  通过ID查询串口句柄
 *
 * @param[in]:  id  -   串口PLUM ID
 *
 * @return: 返回串口操作句柄指针
 **/
PLUM_PRIVATE struct stm32_uart *hal_stm32_uart_instance_select(plum_u32 id)
{
    USART_TypeDef *instance = NULL;
    switch (PLUM_HAL_UART_IDX(id)) {
#if defined(LPUART1)
        case 0:
            instance = LPUART1;
            break;
#endif

#if defined(USART1)
        case 1:
            instance = USART1;
            break;
#elif defined(UART1)
        case 1:
            instance = UART1;
            break;
#endif

#if defined(USART2)
        case 2:
            instance = USART2;
            break;
#elif defined(UART2)
        case 2:
            instance = UART2;
            break;
#endif

#if defined(USART3)
        case 3:
            instance = USART3;
            break;
#elif defined(UART3)
        case 3:
            instance = UART3;
            break;
#endif

#if defined(USART4)
        case 4:
            instance = USART4;
            break;
#elif defined(UART4)
        case 4:
            instance = UART4;
            break;
#endif

#if defined(USART5)
        case 5:
            instance = USART5;
            break;
#elif defined(UART1)
        case 5:
            instance = UART5;
            break;
#endif

        default:
            break;
    }

    struct stm32_uart *ptr = uarts_hd.next;

    while (ptr) {
        if (ptr->huart.Instance == instance) {
            break;
        }
        ptr = ptr->next;
    }

    return (ptr);
}

/*
 * @brief:  通过PLUM ID注册串口句柄
 *
 * @param[in]:  id  -   串口PLUM ID
 *
 * @return: 返回串口句柄
 */
PLUM_PRIVATE struct stm32_uart *hal_stm32_uart_instance_register(plum_u32 id)
{
    struct stm32_uart *uart_hdl =
        plum_kal_mem_malloc(sizeof(struct stm32_uart));
    if (!uart_hdl) {
        return NULL;
    }

    memset(uart_hdl, 0, sizeof(struct stm32_uart));
    switch (PLUM_HAL_UART_IDX(id)) {
#if defined(LPUART1)
        case 0:
            uart_hdl->huart.Instance = LPUART1;
            break;
#endif
#if defined(USART1)
        case 1:
            uart_hdl->huart.Instance = USART1;
            break;
#elif defined(UART1)
        case 1:
            uart_hdl->huart.Instance = UART1;
            break;
#endif

#if defined(USART2)
        case 2:
            uart_hdl->huart.Instance = USART2;
            break;
#elif defined(UART2)
        case 2:
            uart_hdl->huart.Instance = UART2;
            break;
#endif

#if defined(USART3)
        case 3:
            uart_hdl->huart.Instance = USART3;
            break;
#elif defined(UART3)
        case 3:
            uart_hdl->huart.Instance = UART3;
            break;
#endif
#if defined(USART4)
        case 4:
            uart_hdl->huart.Instance = USART4;
            break;
#elif defined(UART4)
        case 4:
            uart_hdl->huart.Instance = UART4;
            break;
#endif
#if defined(USART5)
        case 5:
            uart_hdl->huart.Instance = USART5;
            break;
#elif defined(UART5)
        case 5:
            uart_hdl->huart.Instance = UART5;
            break;
#endif
        default:
            plum_kal_mem_malloc(uart_hdl);
            return NULL;
    }

    struct stm32_uart *ptr = &uarts_hd;
    do {
        if (!ptr->next) {
            ptr->next = uart_hdl;
            break;
        }
        else if (ptr->next->huart.Instance == uart_hdl->huart.Instance) {

            plum_kal_mem_malloc(uart_hdl);
            uart_hdl = ptr;
            break;
        }

        ptr = ptr->next;
    } while (ptr->next);

    return (uart_hdl);
}

/*
 * @brief:  通过串口huart查询串口句柄
 *
 * @param[in]:  huart  -   HAL串口句柄
 *
 * @return: 返回串口句柄
 */
PLUM_PRIVATE struct stm32_uart *hal_stm32_uart_handle(UART_HandleTypeDef *huart)
{
    struct stm32_uart *ptr = uarts_hd.next;
    ;

    while (ptr) {
        if (ptr->huart.Instance == huart->Instance) {
            break;
        }
        ptr = ptr->next;
    }

    return (ptr);
}

PLUM_PRIVATE plum_u32 hal_stm32_uart_wordlen(plum_hal_uart_databit_t databit)
{
    plum_u32 rc = 0xFFFF;

    switch (databit) {
        case PLUM_HAL_UART_DATABIT_5:
#if defined(UART_WORDLENGTH_5B)
            rc = UART_WORDLENGTH_5B;
#endif
            break;

        case PLUM_HAL_UART_DATABIT_6:
#if defined(UART_WORDLENGTH_6B)
            rc = UART_WORDLENGTH_6B;
#endif
            break;

        case PLUM_HAL_UART_DATABIT_7:
#if defined(UART_WORDLENGTH_7B)
            rc = UART_WORDLENGTH_7B;
#endif
            break;

        case PLUM_HAL_UART_DATABIT_8:
            rc = UART_WORDLENGTH_8B;
            break;

        case PLUM_HAL_UART_DATABIT_9:
            rc = UART_WORDLENGTH_9B;
            break;
    }

    return (rc);
}

PLUM_PRIVATE plum_u32 hal_stm32_uart_stopbit(plum_hal_uart_stopbit_t stopbit)
{
    plum_u32 rc = 0xFFFF;

    switch (stopbit) {
        case PLUM_HAL_UART_STOPBIT_1:
            rc = UART_STOPBITS_1;
            break;

        case PLUM_HAL_UART_STOPBIT_1_5:
#if defined(UART_STOPBITS_1_5)
            rc = UART_STOPBITS_1_5;
#endif
            break;

        case PLUM_HAL_UART_STOPBIT_2:
            rc = UART_STOPBITS_2;
            break;
    }

    return (rc);
}

PLUM_PRIVATE plum_u32 hal_stm32_uart_parity(plum_hal_uart_parity_t parity)
{
    plum_u32 rc = 0xFFFF;

    switch (parity) {
        case PLUM_HAL_UART_PARITY_NONE:
            rc = UART_PARITY_NONE;
            break;
        case PLUM_HAL_UART_PARITY_EVEN:
            rc = UART_PARITY_EVEN;
            break;
        case PLUM_HAL_UART_PARITY_ODD:
            rc = UART_PARITY_ODD;
            break;
    }

    return (rc);
}

PLUM_PRIVATE plum_u32
    hal_stm32_uart_flow_ctrl(plum_hal_uart_flow_ctrl_t flowctrl)
{
    plum_u32 rc = 0xFFFF;

    switch (flowctrl) {
        case PLUM_HAL_UART_FLOW_CTRL_NONE:
            rc = UART_HWCONTROL_NONE;
            break;
        case PLUM_HAL_UART_FLOW_CTRL_CTS:
            rc = UART_HWCONTROL_CTS;
            break;
        case PLUM_HAL_UART_FLOW_CTRL_RTS:
            rc = UART_HWCONTROL_RTS;
            break;
        case PLUM_HAL_UART_FLOW_CTRL_RTS_CTS:
            rc = UART_HWCONTROL_RTS_CTS;
            break;
    }

    return (rc);
}

PLUM_PRIVATE plum_void hal_stm32_uart_clk_enable(struct stm32_uart *uart)
{
    if (!uart) {
        return;
    }

#if defined(USART1)
    if (uart->huart.Instance == USART1) {
        __HAL_RCC_USART1_CLK_ENABLE();
    }
#elif defined(UART1)
    if (uart->huart.Instance == UART1) {
        __HAL_RCC_UART1_CLK_ENABLE();
    }
#endif
#if defined(USART2)
    else if (uart->huart.Instance == USART2) {
        __HAL_RCC_USART2_CLK_ENABLE();
    }
#elif defined(UART2)
    else if (uart->huart.Instance == UART2) {
        __HAL_RCC_UART2_CLK_ENABLE();
    }
#endif
#if defined(USART3)
    else if (uart->huart.Instance == USART3) {
        __HAL_RCC_USART3_CLK_ENABLE();
    }
#elif defined(UART3)
    else if (uart->huart.Instance == UART3) {
        __HAL_RCC_UART3_CLK_ENABLE();
    }
#endif
#if defined(USART4)
    else if (uart->huart.Instance == USART4) {
        __HAL_RCC_USART4_CLK_ENABLE();
    }
#elif defined(UART4)
    else if (uart->huart.Instance == UART4) {
        __HAL_RCC_UART4_CLK_ENABLE();
    }
#endif
#if defined(USART5)
    else if (uart->huart.Instance == USART5) {
        __HAL_RCC_USART5_CLK_ENABLE();
    }
#elif defined(UART5)
    else if (uart->huart.Instance == UART5) {
        __HAL_RCC_UART5_CLK_ENABLE();
    }
#endif
#if defined(LPUART1)
    else if (uart->huart.Instance == LPUART1) {
        __HAL_RCC_LPUART1_CLK_ENABLE();
    }
#endif
}

PLUM_PRIVATE plum_void hal_stm32_uart_irq_enable(struct stm32_uart *uart)
{
    if (!uart) {
        return;
    }

    plum_s8 irq_line = 0xFF;

#if defined(USART1)
    if (uart->huart.Instance == USART1) {
        irq_line = USART1_IRQn;
    }
#elif defined(UART1)
    if (uart->huart.Instance == UART1) {
        irq_line = UART1_IRQn;
    }
#endif
#if defined(USART2)
    else if (uart->huart.Instance == USART2) {
        irq_line = USART2_IRQn;
    }
#elif defined(UART2)
    else if (uart->huart.Instance == UART2) {
        irq_line = UART2_IRQn;
    }
#endif
#if defined(USART3)
    else if (uart->huart.Instance == USART3) {
        irq_line = USART3_IRQn;
    }
#elif defined(UART3)
    else if (uart->uart_handle.Instance == UART3) {
        irq_line = UART3_IRQn;
    }
#endif
#if defined(USART4)
    else if (uart->huart.Instance == USART4) {
        irq_line = USART4_IRQn;
    }
#elif defined(UART4)
    else if (uart->huart.Instance == UART4) {
        irq_line = UART4_IRQn;
    }
#endif
#if defined(USART5)
    else if (uart->huart.Instance == USART5) {
        irq_line = USART5_IRQn;
    }
#elif defined(UART5)
    else if (uart->huart.Instance == UART5) {
        irq_line = UART5_IRQn;
    }
#endif
#if defined(LPUART1)
    else if (uart->huart.Instance == LPUART1) {
        irq_line = LPUART1_IRQn;
    }
#endif

    if (irq_line != 0xFF) {
        HAL_NVIC_SetPriority((IRQn_Type)irq_line, 3, 0);
        HAL_NVIC_EnableIRQ((IRQn_Type)irq_line);
    }
}

/*****************************************************************************
 * Interrupt Functions
 ****************************************************************************/

void USART1_IRQHandler(void)
{
    struct stm32_uart *uart1 =
        hal_stm32_uart_instance_select(PLUM_HAL_UART_ID(1));
    HAL_UART_IRQHandler(&uart1->huart);
}

/**
 * @brief  Rx Transfer completed callback.
 * @param  huart UART handle.
 */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    struct stm32_uart *uart = hal_stm32_uart_handle(huart);

    if (uart) {
        fifo_write(uart->rxfifo, &uart->rxbyte, 1);

        HAL_UART_Receive_IT(&uart->huart, &uart->rxbyte, 1);
    }
}

void HAL_UART_IdleCallback(UART_HandleTypeDef *huart)
{
    struct stm32_uart *uart = hal_stm32_uart_handle(huart);
    if (uart) {
    }
}

/*****************************************************************************
 * Public Functions
 ****************************************************************************/

PLUM_PUBLIC
plum_s32 plum_hal_uart_init(plum_u32 id, plum_hal_uart_cof_t *config)
{
    if (!PLUM_HAL_ID_IS_UART(id)) {
        return (PLUM_ECODE_EPARA);
    }

    struct stm32_uart *uart = hal_stm32_uart_instance_register(id);
    if (!uart) {
        return (PLUM_ECODE_EMEM);
    }

    plum_hal_gpio_cof_t gpio;
    gpio.mode = PLUM_HAL_GPIO_MODE_COMMON;

    gpio.config.com = PLUM_HAL_GPIO_MODE_AF_PP;
    plum_hal_gpio_init(config->txpin_id, &gpio);

    gpio.config.com = PLUM_HAL_GPIO_MODE_INPUT;
    plum_hal_gpio_init(config->rxpin_id, &gpio);

    hal_stm32_uart_clk_enable(uart);
    uart->huart.Init.BaudRate   = config->baudrate;
    uart->huart.Init.WordLength = hal_stm32_uart_wordlen(config->databit);
    uart->huart.Init.StopBits   = hal_stm32_uart_stopbit(config->stopbit);
    uart->huart.Init.Parity     = hal_stm32_uart_parity(config->parity);
    uart->huart.Init.HwFlowCtl  = hal_stm32_uart_flow_ctrl(config->flowctrl);

    uart->huart.Init.Mode         = UART_MODE_TX_RX;
    uart->huart.Init.OverSampling = UART_OVERSAMPLING_16;
#if defined(STM32F1XX)
    uart->huart.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
    uart->huart.Init.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
#endif
    if (HAL_UART_Init(&uart->huart) != HAL_OK) {
        return (PLUM_ECODE_EIO);
    }

    uart->rxfifo = fifo_init(config->rxbuf_size);
    if (!uart->rxfifo) {
        return (PLUM_ECODE_EMEM);
    }

    HAL_UART_Receive_IT(&uart->huart, &uart->rxbyte, 1);
    hal_stm32_uart_irq_enable(uart);

    return (PLUM_ECODE_OK);
}

PLUM_PUBLIC
plum_s32 plum_hal_uart_send(plum_u32 id, PLUM_CONST plum_void *data,
                            plum_u16 cnt)
{
    struct stm32_uart *uart = hal_stm32_uart_instance_select(id);
    if (!uart) {
        return (PLUM_ECODE_EIO);
    }

    if (!data) {
        return (PLUM_ECODE_EMEM);
    }

    HAL_UART_Transmit(&uart->huart, (plum_u8 *)data, cnt, 1000);
    while (!(uart->huart.Instance->SR & UART_FLAG_TXE))
        ;

    return (PLUM_ECODE_OK);
}

PLUM_PUBLIC
plum_s32 plum_hal_uart_recv(plum_u32 id, plum_void *data, plum_u16 size,
                            plum_u32 timeout)
{
    plum_s32 rc = PLUM_ECODE_OK;

    do {
        struct stm32_uart *uart = hal_stm32_uart_instance_select(id);
        if (!uart) {
            rc = (PLUM_ECODE_EIO);
            break;
        }

        if (!data) {
            rc = (PLUM_ECODE_EMEM);
            break;
        }

        plum_u16 cur  = 0;
        plum_u16 last = 0;
        while (--timeout) {
            cur = fifo_payload(uart->rxfifo);
            if (cur != last) {
                last = cur;
            }
            else if (cur) {
                break;
            }

            HAL_Delay(1);
        }

        if (cur) {
            if (cur >= size) {
                fifo_read(uart->rxfifo, data, size);
                rc = size;
            }
            else {
                fifo_read(uart->rxfifo, data, cur);
                rc = cur;
            }
        }
    } while (0);

    return (rc);
}

/****************************************************************************/
/*                                                                          */
/*  End of file.                                                            */
/*                                                                          */
/****************************************************************************/
